package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Rules2;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {
    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    public Result<?> login(@RequestBody User users){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getSno, users.getSno()).eq(User::getPassword,users.getPassword()));
        if(res==null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success(res);
    }
    @PostMapping("/register")
    public Result<?> register(@RequestBody User users){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getSno, users.getSno()));
        if(res !=null){
            return Result.error("-1","用户名重复!");
        }
        if(users.getPassword()==null){
            users.setPassword("123456");
        }
        return Result.success();
    }
    @PostMapping
    public Result<?> save(@RequestBody User users){
        if(users.getPassword()==null){
            users.setPassword(("123456"));
        }
        userMapper.insert(users);
        return Result.success();
    }
    @PutMapping
    public Result<?> update(@RequestBody User users){
        userMapper.updateById(users);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {

        userMapper.deleteById(id);
        return Result.success();
    }
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search,
                              @RequestParam(required = false) Integer sno){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(User::getSname,search);
        }
        if (sno != null) { // 判断学号参数是否为空
            wrapper.eq(User::getSno, sno); // 根据学号查询
        }

        Page<User> usersPage=userMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(usersPage);
    }


}

